<?php
/**
 * ClassName: Tool
 * Description: 通用工具类
 * @Author 周昌
 * @Create 2023/11/7 17:11
 */

namespace libs;


class Tool
{
    public static function createResult($code, $msg, $data = null)
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];

        return $result;

    }

    public static function Success($msg = null,$data='')
    {
        if (is_string($data)) {
            $msg_tmp = $msg;
//            $msg = $data;
            $data = is_array($msg_tmp) ? $msg_tmp : [];
        }
        if (!$msg) {
            $msg = "成功";
        }
       return self::createResult(1, $msg, $data);
    }

    public static function Error($msg = null,$data='')
    {
        if (is_string($data)) {
            $msg_tmp = $msg;
//            $msg = $data;
            $data = is_array($msg_tmp) ? $msg_tmp : [];
        }
        if (!$msg) {
            $msg = "失败";
        }
        return self::createResult(0, $msg, $data);

    }
    //根据出生日期计算年龄
    public static function getAgeByBirth($birth){

        $age = 0;
        $year = date('Y', strtotime($birth));
        $month = date('m', strtotime($birth));
        $day = date('d', strtotime($birth));

        $now_year = date('Y');
        $now_month = date('m');
        $now_day = date('d');

        if ($now_year > $year) {
            $age = $now_year - $year - 1;
            if ($now_month > $month) {
                $age++;
            } else if ($now_month == $month) {
                if ($now_day >= $day) {
                    $age++;
                }
            }
        }
        return $age;
    }
    public static function getDomain(){
        $ssl=isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] === '443' ? 'https://' : 'http://';
        $domain=$ssl.$_SERVER['HTTP_HOST'].'/';
        return $domain;
    }

    /**
     * #User: Administrator
     * #Time: 2023/12/27 9:17
     * #Author:周昌
     * #Description: 上传存储桶返回文件增加访问域名
     * @param string/array $url
     * @return array|mixed|string|string[]
     */
    public static function ossAddDomain($url)
    {
        $domain='https://cyz.oss-cn-north-2.unicloudsrv.com/';
        if(is_array($url)){
            $url=array_map(function ($value)use ($domain){
                return strpos($value,$domain)===false?$domain.$value:$value;
            },$url);

        }elseif(is_string($url)){
            $url=strpos($url,$domain)===false?$domain.$url:$url;
        }
        return $url;

    }
    /**
     * #User: Administrator
     * #Time: 2023/12/28 9:38
     * #Author:周昌
     * #Description: 将字符串省多余部分省略为...
     * @param string $text
     * @param integer $length
     * @return string
     */
    public static function strOmit($text,$length=10)
    {
        if(mb_strlen($text)>$length){
            $text = mb_strimwidth($text, 0, $length, '...');
        }
        return $text;
    }
}